/** 
 * Copyright (C), 2010-2012, AIYOU Software Co.,Ltd. ALL RIGHTS RESERVED. 
 * File name:ShareAction.java
 * Version:1.0
 * Date:2011-12-12
 * Description: 分享Action
 * author:zhijian.zhang
 */
package com.tietiao.action.share;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.tietiao.common.action.BaseAction;
import com.tietiao.common.constants.CommodityConstants;
import com.tietiao.common.json.JsonControllerHelper;
import com.tietiao.common.util.DateFormater;
import com.tietiao.common.util.FileUtil;
import com.tietiao.common.util.ImageUtils;
import com.tietiao.common.util.PropertyUtil;
import com.tietiao.common.util.StringUtil;
import com.tietiao.dao.model.UserCommidityFavorite;
import com.tietiao.service.bean.CommodityBean;
import com.tietiao.service.commodity.CommodityService;
import com.tietiao.service.label.LabelService;
import com.tietiao.service.tietiao.CommidityFavoriteService;

@SuppressWarnings("serial")
@Controller
@Scope("prototype")
public class ShareAction extends BaseAction {
	@Resource
	private CommodityService commodityService;
	@Resource
	private LabelService labelService;
	@Resource
	private CommidityFavoriteService commidityFavoriteService;
	// 接收表单信息BEAN
	private CommodityBean commodityBean;

	private File commodityPic;

	private String commodityPicFileName;
	/**
	 * 用户标签
	 */
	private List<String> userCommonLables;
	
	private List<String> commonLables;

	/**
	 * @return the commonLables
	 */
	public List<String> getCommonLables() {
		return commonLables;
	}

	/**
	 * @param commonLables the commonLables to set
	 */
	public void setCommonLables(List<String> commonLables) {
		this.commonLables = commonLables;
	}

	/**
	 * @return the labelService
	 */
	public LabelService getLabelService() {
		return labelService;
	}

	/**
	 * @param labelService the labelService to set
	 */
	public void setLabelService(LabelService labelService) {
		this.labelService = labelService;
	}

	/**
	 * 我的收藏夹列表
	 */
	private List<UserCommidityFavorite> userCommidityFavorites;

	public List<UserCommidityFavorite> getUserCommidityFavorites() {
		return userCommidityFavorites;
	}

	public void setUserCommidityFavorites(
			List<UserCommidityFavorite> userCommidityFavorites) {
		this.userCommidityFavorites = userCommidityFavorites;
	}

	/**
	 * @return the userCommonLables
	 */
	public List<String> getUserCommonLables() {
		return userCommonLables;
	}

	/**
	 * @param userCommonLables
	 *            the userCommonLables to set
	 */
	public void setUserCommonLables(List<String> userCommonLables) {
		this.userCommonLables = userCommonLables;
	}

	/**
	 * @return the commodityPic
	 */
	public File getCommodityPic() {
		return commodityPic;
	}

	/**
	 * @param commodityPic
	 *            the commodityPic to set
	 */
	public void setCommodityPic(File commodityPic) {
		this.commodityPic = commodityPic;
	}

	/**
	 * @return the commodityPicFileName
	 */
	public String getCommodityPicFileName() {
		return commodityPicFileName;
	}

	/**
	 * @param commodityPicFileName
	 *            the commodityPicFileName to set
	 */
	public void setCommodityPicFileName(String commodityPicFileName) {
		this.commodityPicFileName = commodityPicFileName;
	}

	/**
	 * @return the commodityBean
	 */
	public CommodityBean getCommodityBean() {
		return commodityBean;
	}

	/**
	 * @param commodityBean
	 *            the commodityBean to set
	 */
	public void setCommodityBean(CommodityBean commodityBean) {
		this.commodityBean = commodityBean;
	}

	/**
	 * 
	 * 功能：进入分享主页
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-12
	 * 
	 * @return
	 */
	public String shareIndex() {
		userCommonLables = labelService.getPersionCommonLables(getUser()
				.getUserId());
		userCommidityFavorites = commidityFavoriteService
				.getUserCommidityFavorites(getUser().getUserId(),
						"CREATE_TIME DESC");
		
		commonLables = new ArrayList<String>();
		
		String[] sysCommonLables = PropertyUtil.getValue("SYS_COMMON_USER_LABEL").split(" ");
		for (int i = 0; i < sysCommonLables.length; i++) {
			String lable = sysCommonLables[i];
				commonLables.add(lable);
		}
		if (userCommidityFavorites == null
				|| userCommidityFavorites.size() == 0) {
			UserCommidityFavorite userCommidityFavorite = new UserCommidityFavorite();
			userCommidityFavorite.setCreateTime(new Date());
			userCommidityFavorite.setDefaultType(1);
			userCommidityFavorite.setFavoriteName("未分类");
			userCommidityFavorite.setUserId(getUser().getUserId());
			commidityFavoriteService
					.addUserCommidityFavorite(userCommidityFavorite);
			userCommidityFavorites = new ArrayList<UserCommidityFavorite>();
			userCommidityFavorites.add(userCommidityFavorite);
		}
		return dispatcher("/jsp/fg/share/share.jsp");
	}

	/**
	 * 
	 * 功能： 分享
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-12
	 * 
	 * @return
	 */
	public String share() {
		commodityBean.getCommodityInfo().setUploaderId(getUser().getUserId());
		commodityBean.getCommodityInfo().setUploaderTime(new Date());
		commodityService.shareCommdityInfo(commodityBean);
		return redirect("/share_share_shareIndex.htm");
	}

	/**
	 * 
	 * 功能：上传图片
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-14
	 * 
	 * @return
	 * @throws Exception
	 */
	public String upload() throws Exception {
		Map<String, String> res = new HashMap<String, String>();
		if (commodityPic == null
				|| !StringUtil.checkStrIsNotNull(commodityPicFileName)) {
			res.put("flag", "false");
			res.put("errorCode", "0");
			res.put("errorMsg", "您尚未选择图片!请重试");
		}
		int checkFlag = checkUploadFiles(commodityPic, commodityPicFileName);
		if (checkFlag == 1) {
			String uuid = UUID.randomUUID().toString();

			String suffix = commodityPicFileName.substring(commodityPicFileName
					.indexOf("."));
			// 原始图片文件名
			String picName = uuid + suffix;

			// 切图图片名
			String qietuOneName = uuid + "one" + suffix;

			String datePath = DateFormater.YEAR_MONTH_DAY_FILE_FORMATER
					.format(new Date());

			String rooPath = CommodityConstants.ROOT_FILE_PATH + "/" + datePath;

			File f = new File(rooPath);
			if (!f.exists()) {
				f.mkdirs();
			}
			try {
				// 原始图
				FileUtil.writeFile(commodityPic, new File(rooPath + "/"
						+ picName));

				// 切第一个图
				ImageUtils.equimultipleConvert(
						CommodityConstants.QIETU_ONE_WIDTH,
						CommodityConstants.QIETU_ONE_HEIGHT, commodityPic,
						new File(rooPath + "/" + qietuOneName));

				// 判断是否切第二个图
				if (CommodityConstants.QIETU_TWO_HEIGHT != 0
						&& CommodityConstants.QIETU_TWO_WIDTH != 0) {
					ImageUtils.equimultipleConvert(
							CommodityConstants.QIETU_ONE_WIDTH,
							CommodityConstants.QIETU_ONE_HEIGHT, commodityPic,
							new File(rooPath + "/" + uuid + "two" + suffix));
				}

			} catch (Exception e) {
				e.printStackTrace();
				res.put("flag", "false");
				res.put("errorCode", "0");
				res.put("errorMsg", "上传图片出现异常，请重试!");
			}
			String imgPath = PropertyUtil.getValue("PIC_SERVER") + "/"
					+ datePath + "/" + uuid + "one" + suffix;
			res.put("flag", "true");
			res.put("errorCode", "0");
			res.put("imgRelPath", imgPath);
			res.put("imgPath", datePath + "/" + picName);
		} else {
			res.put("flag", "false");
			res.put("errorCode", String.valueOf(checkFlag));

		}
		JsonControllerHelper.writeJsonToResponse(response, res);
		return null;
	}

	/**
	 * 
	 * 功能：检查上传的文件是否符合限制条件
	 * 
	 * @author: zhijian.zhang
	 * @Date: 2011-12-14
	 * 
	 * @param file
	 *            要上传的文件
	 * @param fileName
	 *            文件名称
	 * @return 1-符合条件 -1-图片大小太大 -2-图片格式不符合限制条件 -3-分辨率不对
	 * @throws IOException
	 */
	private int checkUploadFiles(File file, String fileName) throws IOException {
		if (PropertyUtil.getValue("COMMODITY_ALL0W_FILE_SUFFIX").contains(
				fileName.substring(fileName.indexOf(".")).toLowerCase())) {
			if (file.length() <= Long.valueOf(PropertyUtil
					.getValue("COMMODITY_ALLOW_FILE_MAX_SIZE"))) {

				FileInputStream fis = new FileInputStream(file);
				BufferedImage bufferedImg = ImageIO.read(fis);
				int imgWidth = bufferedImg.getWidth();
				int imgHeight = bufferedImg.getHeight();

				String[] minResolution = PropertyUtil.getValue(
						"COMMODITY_ALLOW_MIN_IMG_RESOLUTION").split("\\*");
				String[] maxResolution = PropertyUtil.getValue(
						"COMMODITY_ALLOW_MAX_IMG_RESOLUTION").split("\\*");

				if (imgWidth >= Integer.parseInt(minResolution[0])
						&& imgWidth <= Integer.parseInt(maxResolution[0])
						&& imgHeight >= Integer.parseInt(minResolution[1])
						&& imgHeight <= Integer.parseInt(maxResolution[1])) {
					return 1;
				} else {
					return -3;
				}
			} else {
				return -1;
			}
		} else {
			return -2;
		}
	}

}
